package cn.gson.oasys.controller;

import cn.gson.oasys.mappers.NoticeMapper;
import cn.gson.oasys.model.dao.system.TypeDao;
import cn.gson.oasys.model.dao.user.UserDao;
import cn.gson.oasys.model.entity.mail.Mailreciver;
import cn.gson.oasys.model.entity.notice.NoticeUserRelation;
import cn.gson.oasys.model.entity.notice.NoticesList;
import cn.gson.oasys.model.entity.plan.Plan;
import cn.gson.oasys.model.entity.process.Notepaper;
import cn.gson.oasys.model.entity.process.ProcessList;
import cn.gson.oasys.model.entity.schedule.ScheduleList;
import cn.gson.oasys.model.entity.system.SystemStatusList;
import cn.gson.oasys.model.entity.system.SystemTypeList;
import cn.gson.oasys.model.entity.task.Taskuser;
import cn.gson.oasys.model.entity.user.User;
import cn.gson.oasys.model.entity.user.UserLog;
import cn.gson.oasys.services.address.DirectorService;
import cn.gson.oasys.services.attendce.AttendceService;
import cn.gson.oasys.services.daymanage.DaymanageService;
import cn.gson.oasys.services.discuss.DiscussService;
import cn.gson.oasys.services.file.FileService;
import cn.gson.oasys.services.inform.InformRelationService;
import cn.gson.oasys.services.inform.InformService;
import cn.gson.oasys.services.mail.MailServices;
import cn.gson.oasys.services.note.NotePaperService;
import cn.gson.oasys.services.plan.PlanService;
import cn.gson.oasys.services.process.ProcessService;
import cn.gson.oasys.services.system.MenuSysService;
import cn.gson.oasys.services.system.StatusService;
import cn.gson.oasys.services.system.TypeService;
import cn.gson.oasys.services.task.TaskService;
import cn.gson.oasys.services.user.UserLogService;
import cn.gson.oasys.services.user.UserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/")
public class IndexController {

	Logger log = LoggerFactory.getLogger(getClass());

	@Autowired
	private UserService userService;

	@Autowired
	private MenuSysService menuService;

	@Autowired
	private NoticeMapper noticeMapper;

	@Autowired
	private StatusService statusService;

	@Autowired
	private TypeService typeService;

	@Autowired
	private TypeDao typeDao;

	@Autowired
	private UserDao uDao;

	@Autowired
	private AttendceService attendceService;

	@Autowired
	private DirectorService directorService;

	@Autowired
	private DiscussService discussService;

	@Autowired
	private FileService fileService;

	@Autowired
	private PlanService planService;

	@Autowired
	private NotePaperService notePaperService;

	@Autowired
	private UserLogService userLogService;

	@Autowired
	private ProcessService processService;

	@Autowired
	private MailServices mailServices;

	@Autowired
	private TaskService taskService;

	@Autowired
	private DaymanageService daymanageService;

	@Autowired
	private InformService informService;

	@Autowired
	private InformRelationService informrelationservice;
	
	// 格式转化导入，该类主要就是判断是否能够类型转化,可以的话就转化
	DefaultConversionService service = new DefaultConversionService();

	@RequestMapping("index")
	public String index(HttpServletRequest request, Model model) {

		HttpSession session = request.getSession();
		if (!StringUtils.isNotBlank(session.getAttribute("userId")+"")) {
			return "login/login";
		}

		Long userId = Long.parseLong(session.getAttribute("userId") + "");
		User user = userService.getUserById(userId);

		//获取该用户可操作的菜单
		menuService.findMenuSys(request,user);
		
		List<ScheduleList> aboutmenotice = daymanageService.aboutmeschedule(userId);

		System.out.println(aboutmenotice);

		for (ScheduleList scheduleList : aboutmenotice) {
			if (scheduleList.getIsreminded() != null && !scheduleList.getIsreminded()){
				SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");//24小时制
				String start = simpleDateFormat.format(scheduleList.getStartTime());
				String now = simpleDateFormat.format(new Date());
				try {
					long now2 = simpleDateFormat.parse(now).getTime();
					long start2 = simpleDateFormat.parse(start).getTime();  
					long cha = start2-now2;
					if(0<cha && cha <86400000){//表示未来的计划日程
						NoticesList remindnotices = new NoticesList();
						remindnotices.setTypeId(11l);
						remindnotices.setStatusId(15l);
						remindnotices.setTitle("您有一个日程即将开始");
						remindnotices.setUrl("/daycalendar");
						remindnotices.setUserId(userId);
						remindnotices.setNoticeTime(new Date());
						
						NoticesList remindnoticeok = informService.save(remindnotices);
						
						informrelationservice.save(new NoticeUserRelation(remindnoticeok, user, false));
						
						scheduleList.setIsreminded(true);
						daymanageService.save(scheduleList);
					}
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
		}
		//获取该用户未读的消息
		List<NoticeUserRelation> notice=informrelationservice.findByReadAndUserId(false,user);
		//获取未读邮件
		List<Mailreciver> mail=mailServices.findByReadAndDelAndReciverId(false, false, user);
		//获取用户的新任务
		List<Taskuser>  task=taskService.findByUserIdAndStatusId(user, 3);

		model.addAttribute("notice", notice.size());
		model.addAttribute("mail", mail.size());
		model.addAttribute("task", task.size());
		model.addAttribute("user", user);
		//展示用户操作记录 由于现在没有登陆 不能获取用户id
		List<UserLog> userLogs=userLogService.findByUser(userId);
		request.setAttribute("userLogList", userLogs);

		return "index/index";
	}

	/**
	 * 控制面板主页
	 * 
	 * @param session
	 * @param model
	 * @return
	 */
	@RequestMapping("controlpanelContent")
	public String Content(HttpSession session, Model model, HttpServletRequest request) {
		Long userId = Long.parseLong(session.getAttribute("userId") + "");
		User user=userService.getUserById(userId);
		request.setAttribute("user", user);

		//计算三个模块的记录条数
		request.setAttribute("filenum", fileService.count());
		request.setAttribute("directornum", directorService.count());
		request.setAttribute("discussnum", discussService.count());
		
		List<Map<String, Object>> list = noticeMapper.findMyNoticeLimit(userId);//显示五条我的通知

		model.addAttribute("user", user);

		//封装页面显示的数据
		for (Map<String, Object> map : list) {
			map.put("status", statusService.findOne((Long) map.get("status_id")).getStatusName());
			map.put("type", typeService.findOne((Long) map.get("type_id")).getTypeName());
			map.put("statusColor", statusService.findOne((Long) map.get("status_id")).getStatusColor());
			map.put("userName", userService.getUserById((Long) map.get("user_id")).getUserName());
			map.put("deptName", userService.getUserById((Long) map.get("user_id")).getDept().getDeptName());
		}

		model.addAttribute("noticeList", list);

		//显示用户显示用户当天最新的记录
		/*showalist(model, userId);*/

		//列举几个流程记录
		List<ProcessList> processlist=processService.findlastthree(userId);
		model.addAttribute("processlist", processlist);
		//流程记录有七种状态
		List<SystemStatusList> processstatus = statusService.findByStatusModel("aoa_process_list");
		model.addAttribute("prostatuslist", processstatus);
		
		//工作计划
		List<Plan> plans=planService.findByUserlimit(userId);
		model.addAttribute("planList", plans);
		//类型：日计划/周计划
		List<SystemTypeList> planType = typeService.findByTypeModel("aoa_plan_list");
		//状态：已完成/未完成
		List<SystemStatusList> planStatus = statusService.findByStatusModel("aoa_plan_list");
		model.addAttribute("ptypelist", planType);
		model.addAttribute("pstatuslist", planStatus);
		
		//列举便签
		List<Notepaper> notepapers = notePaperService.findByUserIdOrderByCreateTimeDesc(userId);
		model.addAttribute("notepaperList", notepapers);

		return "systemcontrol/control";
	}

	/*private void showalist(Model model, Long userId) {
		// 显示用户当天最新的记录
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = new Date();
		String nowdate = sdf.format(date);
		Attends aList = attendceService.findlastest(nowdate, userId);
		if (aList != null) {
			String type = typeService.findname(aList.getTypeId());
			model.addAttribute("type", type);
		}
		model.addAttribute("alist", aList);
	}*/
}
